<template>
  <div>
    <div class="fun-btn clearfix">
      <el-button type="primary" size="small" @click="handleJoin">加入利用</el-button>
      <el-button type="primary" size="small" @click="handleAppoint">指定利用</el-button>
      <el-button type="primary" size="small" @click="handleFinish">利用办结</el-button>
      <el-button type="primary" size="small" @click="dialogVisibleDj = true">利用登记</el-button>
      <el-button @click="handleYuanwen" type="primary" size="small">原文列表</el-button>
      <el-button type="primary" size="small" style="float: right" @click="handleGoBack">返回</el-button>
    </div>

    <section class="center">
      <hgroup>
        <label>{{categoryName}}</label> - <span>{{categorySmall}}</span>
      </hgroup>

      <div class="view-main">
          <div class="tm">
            <label>题名：</label>
            <span>{{detailData.tm}}</span>
          </div>
        <div class="yuanwen">
          <pdf-js-iframe :url="pdfSrc" :fileName="detailData.dh + '.pdf'"></pdf-js-iframe>
<!--          <iframe height="100%" width="100%" :src="pdfSrc"></iframe>-->
        </div>
      </div>

    </section>

    <el-drawer
      :title="setDrawer.title"
      :size="setDrawer.size"
      :direction="setDrawer.direction"
      :visible.sync="drawer"
    >
      <avue-crud :option="option"
                 :table-loading="tableLoading"
                 :data="tableData"
                 :page.sync="page"
                 ref="crud"
                 @on-load="yuanwenLoad"
                 @selection-change="selectionChange"
      >
        <template slot-scope="scope" slot="menu">
          <el-button icon="el-icon-view"
                     @click="handleRead(scope.row)"
                     type="text">查看</el-button>
          <el-button icon="el-icon-download"
                     @click="handleDownload(scope.row)"
                     type="text">下载</el-button>
        </template>
      </avue-crud>
    </el-drawer>

    <el-dialog :title="''"
               :width="'80%'"
               top="5vh"
               :destroy-on-close="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="dialogVisible">
      <avue-crud :option="optionUtilize"
                 :table-loading="utilizeLoading"
                 :data="utilizeTableData"
                 :page.sync="utilizePage"
                 @on-load="getDengjiList"
                 ref="crud">
        <template slot-scope="scope" slot="menu">
          <el-button size="small"
                     type="text"
                     icon="el-icon-circle-plus"
                     @click.native="handleJoinUtilize(scope.row)">加入利用</el-button>
        </template>
      </avue-crud>
    </el-dialog>

    <el-dialog :title="'登记'"
               :width="'1240px'"
               top="5vh"
               :destroy-on-close="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="dialogVisibleDj">

      <add-register @handleSuccess="handleSuccess"></add-register>

    </el-dialog>

  </div>
</template>

<script>
import { appointUtilize, getUtilizeListDet, joinUtilize } from '../../../../api/utilize/utilizeQuery'
import { mapFields } from 'vuex-map-fields'
import { mapActions } from 'vuex'
import {
  downloadPdfOriginal, // getOriginal,
  getOriginalImgList,
  getPdfOriginal
} from '../../../../api/electronicsFile/electronicsFile'
import { getObjectURL } from '../../../../util/util'
import { finishDjList, getDjList } from '../../../../api/utilize/utilizeDengji'
import AddRegister from '../registerTemplate/addRegister'
import PdfJsIframe from '../../../../components/showPdf/pdfJsIframe'

export default {
  name: 'viewArchives',
  components: {
    PdfJsIframe,
    AddRegister
  },
  data () {
    return {
      detailData: '',
      pdfSrc: '',
      dialogVisible: false,
      drawer: false,
      setDrawer: {
        title: '',
        size: '',
        direction: 'ltr'
      },
      tableLoading: false,
      tableData: [],
      page: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [20, 40, 60, 80],
        totle: 0
      },
      option: {
        align: 'center',
        menuAlign: 'center',
        header: false,
        border: true,
        size: 'medium',
        height: 'calc(100vh - 140px)',
        index: true, // 显示序号
        indexLabel: '序号', // 显示序号
        selection: false, // 多选
        editBtn: false, // 行内编辑按钮
        delBtn: false, // 行内删除按钮
        viewBtn: false, // 行内查看按钮
        menu: true,
        menuWidth: 160,
        column: [
          {
            label: '文件名',
            prop: 'fileName',
            overHidden: true
          }
        ]
      },
      utilizeLoading: false,
      utilizeTableData: [],
      utilizePage: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [20, 40, 60, 80],
        total: 0
      },
      optionUtilize: {
        align: 'center',
        menuAlign: 'center',
        header: false,
        border: true,
        size: 'medium',
        height: 'calc(100vh - 240px)',
        index: true, // 显示序号
        indexLabel: '序号', // 显示序号
        selection: true, // 多选
        editBtn: false, // 行内编辑按钮
        delBtn: false, // 行内删除按钮
        viewBtn: false, // 行内查看按钮
        menu: true,
        column: [
          {
            label: '登记单号',
            prop: 'registerNo',
            overHidden: true
          },
          {
            label: '利用人',
            prop: 'username',
            overHidden: true
          },
          {
            label: '登记时间',
            prop: 'gmtCreate',
            overHidden: true
          },
          {
            label: '证件号码',
            prop: 'certificateNo',
            overHidden: true
          },
          {
            label: '状态',
            prop: 'applyStatus',
            overHidden: true
          }
        ]
      },
      dialogVisibleDj: false
    }
  },
  mounted () {
    this.getData()
    this.getCategoryAll()
  },
  computed: {
    ...mapFields('currencyDic/getCategoryAll', {
      categoryAll: 'retrieved' // 所有门类
    }),
    categoryName () {
      let name = ''
      if (this.categoryAll) {
        this.categoryAll.map(item => {
          if (item.id === this.$route.query.idCategory) {
            name = item.categoryName
          }
        })
      }
      return name
    },
    categorySmall () {
      let name = ''
      if (this.categoryAll) {
        this.categoryAll.map(item => {
          if (item.id === this.$route.query.idCategory) {
            if (item.categoryType === 'jian') {
            // 件
              name = '组件'
            }
            if (item.categoryType === 'juan' && this.detailData.table_type === 'aj') {
            // 案卷
              name = '案卷'
            }
            if (item.categoryType === 'juan' && this.detailData.table_type === 'jn') {
            // 卷内
              name = '卷内'
            }
          }
        })
      }
      return name
    }
  },
  methods: {
    ...mapActions('currencyDic/getCategoryAll', ['getCategoryAll']),
    handleGoBack () {
      this.$route.meta.keepAlive = true
      this.$router.replace('/utilize/utilizeQuery')
    },
    getData () {
      getUtilizeListDet(this.$route.query.idTable, this.$route.query.id).then(res => {
        this.detailData = res.data.data
      })
      getPdfOriginal(this.$route.query.idTable, this.$route.query.id).then(res => {
        // 请求pdf流文件后转vue-pdf预览用的src
        this.pdfSrc = getObjectURL(res.data)
      })
    },
    handleYuanwen () {
      // 原文列表
      this.drawer = true
      this.setDrawer.title = '原文列表'
      this.setDrawer.size = '60%'
    },
    yuanwenLoad () {
      const param = {
        pageNo: this.page.currentPage,
        pageSize: this.page.pageSize,
        params: [{
          op: 'eq',
          name: 'id_record',
          value: this.$route.query.id
        }]
      }
      this.tableLoading = true
      getOriginalImgList(this.$route.query.idTable, param).then(res => {
        this.tableData = res.data.data.records
        this.page.total = res.data.data.total
        this.tableLoading = false
      })
    },
    selectionChange (val) {
      // 原文选中条目
      console.log(val)
    },
    handleJoin () {
      // 加入利用
      const param = {
        idCategory: this.$route.query.idCategory,
        idRecord: this.$route.query.id,
        idTable: this.$route.query.idTable
      }
      joinUtilize(param).then(() => {
        this.$message.success('加入利用成功！')
      })
    },
    handleAppoint () {
      this.dialogVisible = true
      this.getDengjiList()
    },
    getDengjiList () {
      this.utilizeLoading = true
      const param = {
        pageNo: this.utilizePage.pageNo,
        pageSize: this.utilizePage.pageSize
      }
      getDjList(param).then(res => {
        this.utilizeTableData = res.data.data.list
        this.utilizePage.total = res.data.data.total
        this.utilizeLoading = false
      }).catch(() => {
        this.utilizeLoading = false
      })
    },
    handleJoinUtilize (row) {
      // 指定利用
      const param = {
        idCategory: this.$route.query.idCategory,
        idRecord: this.$route.query.id,
        idTable: this.$route.query.idTable,
        idUseRegister: row.id
      }
      appointUtilize(param).then(() => {
        this.$message.success('加入利用成功！')
      })
    },
    handleFinish () {
      // 办结
      finishDjList().then(() => {
        this.$message.success('办结操作成功!')
      })
    },
    handleSuccess () {
      // 新增成功
      this.dialogVisibleDj = false
      // this.getList()
    },
    handleRead (row) {
      // 查看图片
      downloadPdfOriginal(this.$route.query.idTable, row.id).then(res => {
        const fileType = res.headers['content-type']
        const blob = new Blob([res.data], { type: fileType }) // 构造一个blob对象来处理数据

        window.open(URL.createObjectURL(blob), row.fileName)
      })
    },
    handleDownload (row) {
      // 下载原文
      downloadPdfOriginal(this.$route.query.idTable, row.id).then(res => {
        const fileType = res.headers['content-type']
        console.log(res.headers)
        const blob = new Blob([res.data], { type: fileType }) // 构造一个blob对象来处理数据
        const fileName = row.fileName

        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        // IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a')// 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()// 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link)// 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "../../../../styles/mixin";

  .fun-btn{
    padding-bottom: 8px;
  }

  .center {
    height: calc(100vh - 120px);
    background: #fff;
    border-radius: 5px;
    overflow: hidden;
    hgroup{
      background: #409EFF;
      height: 40px;
      line-height: 40px;
      padding: 0 15px;
      color: #fff;

      label {
        font-size: 16px;
      }
      span {
        font-size: 16px;
      }

      .btn {
        color: #fff;

        &:hover {
          opacity: 0.7;
        }
      }
    }

    .view-main{
      height: calc(100% - 40px);
      overflow-y: auto;
      padding: 12px;
      .tm{
        @include sc(15px, #333);
        padding-bottom: 10px;
      }
      .yuanwen{
        @include wh(100%, calc(100% - 40px))
      }
    }
  }
</style>
